import { valueEquals, isEmpty } from 'element-ui/src/utils/util'

export default {
  directives: {
    // v-load-more指令 Select滚动触底触发
    loadMore: {
      inserted: function(el, binding) {
        const selectDom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        selectDom.addEventListener('scroll', function() {
          if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
            binding.value()
          }
        })
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    // v-model/value
    value: {
      type: [Number, String, Array],
      default: null
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectValue: this.multiple ? [] : {},
      options: [],
      query: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0
    }
  },
  methods: {
    // 滚轮下一页触发
    onNextPage() {
      if (this.total > this.query.pageNum * this.query.pageSize) {
        this.query.pageNum = this.query.pageNum + 1
        this.loadData(false)
      }
    },
    // 搜索触发
    onRemoteMethod(query) {
      this.query.searchValue = query
      this.query.pageNum = 1
      this.loadData(true)
    },
    // 获得焦点触发
    onFocus() {
      const size = this.multiple ? this.value ? this.value.length : 0 : 0
      if (this.options.length <= size) {
        this.query.pageNum = 1
        this.loadData()
      }
    },
    onChange(value) {
      // 避免重复触发change
      if (!valueEquals(this.selectValue, value)) {
        this.$emit('change', value)
      }
    },
    // 清空
    onClear() {
      this.options = []
      this.selectValue = this.multiple ? [] : {}
    },
    // 检查数据是否不存在
    checkDataNotExist(value) {
      let notExist = true

      const list = value instanceof Array ? this.value : [value]
      for (let i = 0; i < this.options.length; i++) {
        if (list.includes(this.options[i].value)) {
          notExist = false
          break
        }
      }
      return notExist
    },
    // 获取下拉选中的文本
    getSelectLabel() {
      // 直接调用el-select组件的data数据获取选中的值，如果el-select升级后可能需要修改这段代码
      const selected = this.$refs.select.selected
      if (selected instanceof Array) {
        const departmentName = []
        this.$refs.select.selected.forEach(res => {
          departmentName.push(res.label)
        })
        return departmentName.join(',')
      } else {
        return selected.label
      }
    }
  },
  mounted() {
    if (!isEmpty(this.value)) {
      this.echoLoadData()
    }
  },
  watch: {
    value(val, oldVal) {
      if (!valueEquals(val, oldVal)) {
        this.echoLoadData()
      }
    }
  }
}
